





type Rule = {

  validator?: Function;
  required?: boolean;
  message?: string;
  trigger: string;
  min?: number;
  max?: number;
};

/**
 * 普通校验
 * @param required 是否必填
 * @param minNum 最新字符数量
 * @param maxNum 最大字符数
 * @returns
 */
const getRules = (required: boolean, minNum?: number, maxNum?: number) => {
  const dataRules: Rule[] = [];
  if (required) {

    dataRules.push({ required: true, message: "", trigger: "blur" });
  }
  if (minNum || maxNum) {
    if (!minNum) {
      minNum = 0;
    }
    if (!maxNum) {
      maxNum = 64;
    }

    dataRules.push({
      min: minNum,
      max: maxNum,
      message:
        minNum == 0
          ? "长度： 不超过 " + maxNum
          : "长度： " + minNum + " 到 " + maxNum,
      trigger: "blur",
    });
  }

  return dataRules;
};

/**
 * 自定义校验（自定义函数）
 * @param validateFunc 自定义校验函数
 * 如：const validatePass = (rule, value, callback) => {callback(new Error(value));};
 * 描述：rule为校验规则 ，value为当前表单值，callback可通过callback(new Error(value));返回错误信息,正确时返回callback();
 * @param required 是否必填
 * @param minNum 最新字符数量
 * @param maxNum 最大字符数
 * @returns
 */
const getCustomRules = (

  validateFunc: any,
  required: boolean,
  minNum?: number,
  maxNum?: number
) => {
  const dataRules: Rule[] = getRules(required, minNum, maxNum);
  dataRules.push({ validator: validateFunc, trigger: "blur" });
  return dataRules;
};

/**
 *自定义校验（正则表达式）
 * @param regEx 正则表达式
 * @param msg 不符合时报错信息
 * @param required
 * @param minNum
 * @param maxNum
 * @returns
 */
const getRegExpRules = (
  validRx: ValidRx,
  required: boolean,
  minNum?: number,
  maxNum?: number
) => {
  const validateFunc = (
    _rule: unknown,
    value: string,
    callback: (arg0?: Error | undefined) => void
  ) => {

    const usernamePattern = validRx.regEx;
    if (!usernamePattern.test(value)) {
      return callback(new Error(validRx.msg));
    }

    return callback();
  };
  return getCustomRules(validateFunc, required, minNum, maxNum);
};

interface ValidRx {
  regEx: RegExp;
  msg: string;
}
/**
 * 预置正则验证表达式
 */
const ValidRxs = {
  loginname: {
    regEx: /^[a-zA-Z][a-zA-Z0-9_-]*$/,
    msg: "必须字母开头，只允许字母、数字或下划线",
  } as ValidRx,
  password: {
    regEx:
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/,
    msg: "必须至少6个字符包含大写字母、小写字母、数字和特殊字符",
  } as ValidRx,
  indexKey: {
    regEx: /^[a-zA-Z0-9_]+$/,
    msg: "只允许字母、数字或下划线",
  } as ValidRx,
};

export default { getRules, getCustomRules, getRegExpRules, ValidRxs };
